package com.ellwood.copyright.framework.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @ProjectName: ell-copyright-pro
 * @PackageName: com.ellwood.copyright.framework.handler
 * @ClassName: MyMetaObjectHandler
 * @Description: //  自动填充配置  --  实现对create_time、update_time等的值自动插入和更新
 * @Author: Ellwood
 * @CreateDate: 2024/11/21 - 15:04
 * @Version: V1.0.0
 */
@Slf4j
@Configuration
public class MyMetaObjectHandler implements MetaObjectHandler {

    private final static String CREATE_BY = "createBy";
    private final static String CREATE_TIME = "createTime";
    private final static String UPDATE_BY = "updateBy";
    private final static String UPDATE_TIME = "updateTime";
    private final static String STATUS = "isState";
    private final static String VERSION = "version";
    private final static String DELETED = "isDeleted";

    LocalDateTime now = LocalDateTime.now();

    /**
     * 新增时调用自动填充数据
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill .......");

        // 自动填充状态字段，先检查字段是否已经设置了值，如果没有设置则设置默认值
        Object fieldValue = getFieldValByName(STATUS, metaObject);
        if (fieldValue==null) {
            setFieldValByName(STATUS, 0, metaObject);
        }

        // 自动填充乐观锁version字段 目前没有咱不设置
        this.strictInsertFill(metaObject, VERSION, Integer.class, 1);

        // 创建者 // TODO 权限控制完成之后再进行设置,这里先写死，后面进行根据登录者进行设置
        this.setFieldValByName(CREATE_BY, 3L, metaObject);

        //  自动填充create_time字段
        this.strictInsertFill(metaObject, CREATE_TIME, () -> now, LocalDateTime.class);
        //  this.setFieldValByName(CREATE_TIME, new Date(), metaObject);

        // 更新者  // TODO 权限控制完成之后再进行设置,这里先写死，后面进行根据登录者进行设置
        this.setFieldValByName(UPDATE_BY, 3L, metaObject);

        //  自动填充create_time、update_time字段
        this.strictInsertFill(metaObject, UPDATE_TIME, () -> now, LocalDateTime.class);
        // this.setFieldValByName(UPDATE_TIME, ()->now, metaObject);

        // 删除标识
        strictInsertFill(metaObject, DELETED, Integer.class, 0);
    }

    /**
     * 修改时调用自动填充数据
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {

        log.info("start insert fill .......");

        // 更新者  // TODO 权限控制完成之后再进行设置,这里先写死，后面进行根据登录者进行设置
        this.setFieldValByName(UPDATE_BY,3L,metaObject);
        this.strictUpdateFill(metaObject, UPDATE_TIME, () -> now, LocalDateTime.class);
//        this.setFieldValByName(UPDATE_TIME,new Date(),metaObject);
    }

}
